﻿#include "ColorComboBox.h"
#include <QPixmap>

static Qt::GlobalColor colorList[15] = {Qt::black, Qt::red, Qt::darkRed,  Qt::green,
                                      Qt::darkGreen, Qt::blue, Qt::darkBlue, Qt::cyan,
                                     Qt::magenta, Qt::darkMagenta, Qt::yellow, Qt::darkYellow,
                                     Qt::gray, Qt::darkGray, Qt::lightGray};
ColorComboBox::ColorComboBox(QWidget *parent)
    :QComboBox(parent)
{

    setIconSize(QSize(16, 16));
    QPixmap pixmap(16, 16);

    pixmap.fill(Qt::black);
    addItem(QIcon(pixmap), tr("black"), QVariant((int) Qt::black));

    pixmap.fill(Qt::red);
    addItem(QIcon(pixmap), tr("red"), QVariant((int) Qt::red));

    pixmap.fill(Qt::darkRed);
    addItem(QIcon(pixmap), tr("dark red"), QVariant((int) Qt::darkRed));

    pixmap.fill(Qt::green);
    addItem(QIcon(pixmap), tr("green"), QVariant((int) Qt::green));

    pixmap.fill(Qt::darkGreen);
    addItem(QIcon(pixmap), tr("dark green"), QVariant((int) Qt::darkGreen));

    pixmap.fill(Qt::blue);
    addItem(QIcon(pixmap), tr("blue"), QVariant((int) Qt::blue));

    pixmap.fill(Qt::darkBlue);
    addItem(QIcon(pixmap), tr("dark blue"), QVariant((int) Qt::darkBlue));

    pixmap.fill(Qt::cyan);
    addItem(QIcon(pixmap), tr("cyan"), QVariant((int) Qt::cyan));

    pixmap.fill(Qt::darkCyan);
    addItem(QIcon(pixmap), tr("dark cyan"), QVariant((int) Qt::darkCyan));

    pixmap.fill(Qt::magenta);
    addItem(QIcon(pixmap), tr("magenta"), QVariant((int) Qt::magenta));

    pixmap.fill(Qt::darkMagenta);
    addItem(QIcon(pixmap), tr("dark magenta"), QVariant((int) Qt::darkMagenta));

    pixmap.fill(Qt::yellow);
    addItem(QIcon(pixmap), tr("yellow"), QVariant((int) Qt::yellow));

    pixmap.fill(Qt::darkYellow);
    addItem(QIcon(pixmap), tr("dark yellow"), QVariant((int) Qt::darkYellow));

    pixmap.fill(Qt::gray);
    addItem(QIcon(pixmap), tr("gray"), QVariant((int) Qt::gray));

    pixmap.fill(Qt::darkGray);
    addItem(QIcon(pixmap), tr("dark gray"), QVariant((int) Qt::darkGray));

    pixmap.fill(Qt::lightGray);
    addItem(QIcon(pixmap), tr("light gray"), QVariant((int) Qt::lightGray));

    connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(onIndexChanged(int)));
}

int ColorComboBox::indexFromColor(QColor c)
{
    //int N = sizeof(colorList);
    for(int idx = 0; idx < 15; idx++)
    {
        QColor cl( colorList[idx] );
        if(cl == c)
        {
            return idx;
        }
    }
    return 0;// 如果没找到则用默认值
}

QColor ColorComboBox::colorFromIndex(int idx)
{
    QColor cl( colorList[idx] );
    return cl;
}

QColor ColorComboBox::color()
{
    int colorValue = currentData(Qt::UserRole).toInt();
    QColor cl( (Qt::GlobalColor )colorValue );
    return cl;
}

void ColorComboBox::onIndexChanged(int)
{
    int colorValue = currentData(Qt::UserRole).toInt();
    QColor cl( (Qt::GlobalColor )colorValue );
    emit colorChanged(cl);
}

ColorComboBox::~ColorComboBox()
{

}

